#include "Common.hpp"
#include "InetAddr.hpp"
#include "log.hpp"
#include <string>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include "ThreadPool.hpp"

using namespace LogModule;
using namespace ThreadPoolModule;

const int defaultsockfd = -1;
const int defaultlog = 8;

 //using task_t=std::function<void()>;

using func_t = std::function<std::string(const std::string &, InetAddr &)>;

class TcpServer : public Nocopy
{

public:
    TcpServer(uint16_t port, func_t func)
        : _port(port),
          _isrunning(false),
          _listensockfd(defaultsockfd), 
          _func(func)
    {
    }

    ~TcpServer()
    {
    }

    void Init()
    {
        // 创建Tcp套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket create error";
            exit(ExitCode::SOCKET_ERR);
        }
        LOG(LogLevel::FATAL) << "socket create success";

        // 进行bind绑定
        InetAddr local(_port);
        int n = bind(_listensockfd, local.GetSockaddr(), local.Getlen());
        if (n != 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(ExitCode::BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";

        // 进行listen监听
        n = listen(_listensockfd, defaultlog);
        if (n != 0)
        {
            LOG(LogLevel::FATAL) << "listen error";
            exit(ExitCode::LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success";
    }

    void Server(int sockfd, InetAddr &addr)
    {
        char buffer[1024];
        while (1)
        {
            ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                LOG(LogLevel::INFO) << addr.StringAddr() << "say#" << buffer;
                // std::string echo_string = "echo#" + std::string(buffer);
                std::string echo_string = _func(buffer, addr);
                ssize_t wn = write(sockfd, echo_string.c_str(), echo_string.size());
                // LOG(LogLevel::INFO) << "write返回值: " << wn;
            }
            else if (n == 0)
            {
                LOG(LogLevel::DEBUG) << addr.StringAddr() << "退出……";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::FATAL) << addr.StringAddr() << "读取失败";
                close(sockfd);
                break;
            }
        }
    }

    class ThreadDate
    {
    public:
        ThreadDate(int sockfd, InetAddr &addr, TcpServer *tcp)
            : _sockfd(sockfd), _addr(addr), _tcp(tcp)
        {
        }

        int _sockfd;
        InetAddr _addr;
        TcpServer *_tcp;
    };

    static void *Routine(void *args)
    {

        pthread_detach(pthread_self());
        ThreadDate *t = static_cast<ThreadDate *>(args);
        t->_tcp->Server(t->_sockfd, t->_addr);

        delete t;
        return nullptr;
    }

    void Run()
    {
        _isrunning = true;
        while (true)
        {
            // 进行获取连接
            sockaddr_in addr;
            socklen_t len = sizeof(addr);
            int sockfd = accept(_listensockfd, COW(addr), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << " accept error";
                continue;
            }
            InetAddr peer(addr);
            LOG(LogLevel::INFO) << peer.StringAddr() << " accept success";

            // 多进程版
            // int pid = fork();
            // if (pid < 0)
            // {
            //     LOG(LogLevel::FATAL) << "fork error";
            //     exit(ExitCode::FORK_ERR);
            // }
            // else if (pid == 0)
            // {
            //     // 关闭listen
            //     close(_listensockfd);
            //     // 再次创建子进程
            //     if (fork() > 0)
            //     {
            //         exit(ExitCode::OK);
            //     }
            //     Server(sockfd, peer);
            //     exit(ExitCode::OK);
            // }
            // else
            // {
            //     close(sockfd);
            //     int rid = waitpid(pid, nullptr, 0);
            //     (void)rid;
            // }

            // Server(sockfd,peer);

            // 多线程版本
            pthread_t t;
            ThreadDate *tp = new ThreadDate(sockfd, peer, this);
            pthread_create(&t, nullptr, Routine, (void *)tp);

            // 线程池版本
            //  ThreadPool<task_t>::GwetInstance()->Enqueue([this,sockfd,peer](){
            //      this->Server(sockfd,peer);

            // });
        }
        _isrunning = false;
    }

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;

    func_t _func;
};
